import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "./auth";
const service = axios.create({
  baseURL: process.env.VUE_APP_SERVET_URL,
  timeout: 5000,
});

// 设置跨域，并设置访问权限，允许跨域携带cookie,使用jwt可关闭
service.defaults.withCredentials = false;

service.interceptors.response.use(
  (response) => {
    const {
      data: res,
      data: { code },
    } = response;

    // 自定义代码 code 不是200 ，判断错误
    if (code !== 200) {
      // 50008 非法token;50012异地登入;50014 token 失效。
      if (code === 401 || code === 50012 || code === 50014) {
        // 重新登入
        ElMessageBox.confirm("会话失效,是否重新登入", "权限不足", {
          confirmButtonText: "OK",
          cancelButtonText: "Cancel",
          type: "warning",
        })
          .then(() => {
            // to login
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "Delete canceled",
            });
          });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message || "error",
          duration: 3000,
        });
      }

      return Promise.reject(new Error(res.message || "error"));
    } else {
      return res.data;
    }
  },
  (error) => {
    console.log("reques", error);
    ElMessage({
      type: "error",
      showClose: true,
      message: error.message || "error",
      duration: 5000,
    });
    return Promise.reject(error);
  }
);

service.interceptors.request.use((config) => {
  // config.headers["Yr-token"] = getToken();
  config.headers["Authorization"] = "Bearer " + getToken();
  return config;
});
//git fetch origin foor:bar;
// git push pull

export default service;
